<template>
<!-- :file-list="fileList" -->
    <el-upload 
        :action="imgUpload.url" 
        :headers="imgUpload.headers" 
        list-type="picture-card" 
        :limit="limit"
        :on-success="handlePictureSuccess" 
        :before-upload="beforeAvatarUpload" 
        :on-preview="handlePictureCardPreview"
        
        >
        <img v-if="imageUrl" :src="imageUrl"  width="170px" height="170px" >
        <!-- :file-list=picUrl -->
        <i class="el-icon-plus"></i>
    </el-upload>
</template>

<script>
import { getToken } from "@/utils/auth";
export default {
    name: 'imageUpload',
    props:['picUrl'],
    mounted(){
        console.log('pic',this.picUrl)
        this.imageUrl = this.picUrl
    },
    data() {
        return {
            limit: 1,
            //页面上存的暂时图片地址List
            fileList: [
                // {
                //     name:"test.jpg",
                //     url:'http://s61q6gwnq.hn-bkt.clouddn.com/Ft76fsNu79poKMzCdh2qXvQm7bgB'
                // }
            ],
            //图片地址
            imageUrl: "",
            //图片名称不含路径的
            nFileName: "",
            fileList:[this.picUrl],
            dialogVisible: false,
            imgUpload: {
                // 设置上传的请求头部
                headers: {
                    Authorization: "Bearer " + getToken()
                },
                // 图片上传的方法地址:
                url: process.env.VUE_APP_BASE_API + "/bookManage/addUrl",
            },

        }
    },
    methods: {
        // 文件上传相关
        //图片上传前的相关判断
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg' || file.type == 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 5;
            if (!isJPG) {
                this.$message.error('上传图片只能是 JPG/PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 5MB!');
            }
            return isJPG && isLt2M;
        },

        //图片预览
        handlePictureCardPreview(file) {
            //预览数据测试
            // console.log('预览数据测试', file)
            this.imageUrl = file.url;
            this.dialogVisible = true;
        },

        //图片上传成功后的回调
        handlePictureSuccess(res, file) {
            console.log('组件成功调用',res)
            //向父组件传递图片URL
            this.$emit('getPicUrl',res.data)
            this.imageUrl = res.data
        },
    }
}
</script>

<style></style>